<template>
  <transition name="slide-left">
    <div class="photoWall" v-show="init">
      <div class="title border-bottom">
        <i class="icon-xiangzuo" onclick="window.history.go(-1)"></i>
        我的照片
        <div class="editAdd">
          <span @click="management" v-show="photoList.length">{{edit}}</span>
          <span @click="upload($refs.upload)" v-show="!showEdit">上传</span>
        </div>
      </div>
      <div class="empty" v-if="!photoList.length">
        <p><img src="~common/image/imgEmpty.png" alt=""></p>
        <p>目前还没有照片</p>
        <p>小主人赶紧去添加吧～</p>
      </div>
      <div class="hint">
        <i class="icon-jinggao"></i>
        <span>上传照片后请点击照片，再点击选择使用此张照片</span>
      </div>
      <!--个人图片-->
      <div class="default">
        <yd-slider :loop="false">
          <yd-slider-item v-for="(item,idx) in photoList">
            <ul class="setting-content">
              <li v-for="(it,index) in item">
                <img :src="it.small_path" @click="examine(it.path,it.id,index,1,item)">
                <div class="mask" @click="del(it.id,index,idx)" v-show="showEdit">
                  <i class="icon-del"></i>
                </div>
              </li>
            </ul>
          </yd-slider-item>
        </yd-slider>
      </div>
      <!--系统图片-->
      <div class="sysimage border-top">
        <h3>照片素材</h3>
        <yd-slider :loop="false">
          <yd-slider-item v-for="(item,inx) in systemList">
            <ul>
              <li v-for="(it,index) in item">
                <img :src="it.small_path" @click="examine(it.path,it.id,index,2,item)">
              </li>
            </ul>
          </yd-slider-item>
        </yd-slider>
      </div>
      <yd-popup v-model="operation" position="center" width="80%">
        <div class="operation">
          <p @click="pitchOn" class="border-right">选择该照片</p>
          <p @click="examineBig">查看大图</p>
        </div>
      </yd-popup>
      <!--上传标签-->
      <input type="file" hidden class="upload-file" ref="upload"
             @change="imgUpload($refs.upload)"
             accept="image/*">
      <!--查看大图-->
      <LargerVersion @show="closeShow" v-if="show" :idx="imageIndex" :arrImg="bigPhoto"></LargerVersion>
      <!--loading加载-->
      <Loading v-show="loading"></Loading>
    </div>
  </transition>
</template>


<script>
  import {startUpload, PhotoWall, systemPhotoWall, DeletePhoto} from 'common/js/imgUpload'
  import {islogin} from 'common/js/user'
  import LargerVersion from 'components/largerVersion/largerVersion'
  import {mapGetters, mapMutations} from 'vuex'
  import Loading from 'components/loading/Loading'

  export default {
    data() {
      return {
        init:false,//判断是否登录初始化
        bigPhoto: [],//查看大图
        photoList: [], //图片列表
        systemList: [], //系统图片
        edit: '删除',// 编辑
        showEdit: false,//显示编辑
        operation: false, //是否显示选择
        imageIndex: 1, //索引到查看大图位置
        show: false, //显示查看大图
        imgSrc: '',//选中图片地址
        imgId: '',//选中图片id
      }
    },
    computed: {
      ...mapGetters([
        'loading'
      ]),
    },
    mounted() {
      document.title='照片墙' ;
      //判断是否登录
      islogin().then(res => {
        if (res.status !== 1) {
          this.$dialog.alert({
            mes: '未登录，请先登录', callback: () => {
              this.$router.push('/login');
            }
          });
        } else {
          this.init = true;
          this.$store.dispatch('showLoading');
          //获取照片列表
          this._getPhotowall();
          //获取系统默认图片
          systemPhotoWall({
            "phpsid": localStorage.getItem('token'),//session_id
          }).then(res => {
            if(res.status === 1){
              this.systemList = res.data;
            }
          })
        }
      })
    },
    methods: {
      _getPhotowall(){
        PhotoWall({
          "phpsid": localStorage.getItem('token'),//session_id
        }).then(res => {
          this.$store.dispatch('hideLoading');
          if (res.status === 1) {
            this.photoList = res.data;
            if(!this.photoList.length){
              this.showEdit = false
            }
          }
        });
      },
      //关闭查看大图
      closeShow() {
        this.show = false;
      },
      //查看大图
      examineBig() {
        this.show = true;
        this.operation = false;
      },
      //查看照片
      examine(item, id, index, type, list) {
        switch (type) {
          case 1:
            this.bigPhoto = list;
            break;
          case 2:
            this.bigPhoto = list;
            break;
        }
        this.operation = true;
        this.imageIndex = index;
        this.imgSrc = item;
        this.imgId = id;
      },
      //选中照片
      pitchOn() {
        this.pitchOnImg(this.imgSrc);
        this.pitchOnImgId(this.imgId);
        window.history.back();
      },
      //管理照片
      management() {
        this.showEdit = !this.showEdit;
        if (this.showEdit) {
          this.edit = '完成'
        } else {
          this.edit = '删除'
        }
      },
      //删除图片
      del(id, index,idx) {
        this.$dialog.confirm({
          title: '确定删除？',
          opts: () => {
            DeletePhoto({
              "phpsid": localStorage.getItem('token'),//session_id
              "id": id,//图片id
            }).then(res => {
              this._getPhotowall();
            })
          }
        });
      },
      //选中图片上传
      imgUpload(item) {
        var _this = this;
        var fileObj = item.files[0];
        var quality = .7;
        if (fileObj.size / 1024 > 1025) {
          quality = .4;
        }
        this.$store.dispatch('showLoading');
        //图片压缩
        this.photoCompress(fileObj, {
          quality: quality
        },  (base64Codes) =>{
          let param = new FormData()
          param.append('base64Img', base64Codes)
          param.append('phpsid', localStorage.getItem('token'))
          startUpload(param).then(res => {
            if (res.status === 1) {
              this.$store.dispatch('hideLoading');
              this._getPhotowall();
            }
          })
        });
      },
      photoCompress(file, w, objDiv) {
        var _this = this;
        var ready = new FileReader();
        /*开始读取指定的Blob对象或File对象中的内容. 当读取操作完成时,readyState属性的值会成为DONE,如果设置了onloadend事件处理程序,则调用之.同时,result属性中将包含一个data: URL格式的字符串以表示所读取文件的内容.*/
        ready.readAsDataURL(file);
        ready.onload = function () {
          var re = this.result;
          _this.canvasDataURL(re, w, objDiv)
        }
      },
      //压缩图片
      canvasDataURL(path, obj, callback) {
        var img = new Image();
        img.src = path;
        img.onload = function () {
          var that = this;
          // 默认按比例压缩
          var w = that.width,
            h = that.height,
            scale = w / h;
          w = obj.width || w;
          h = obj.height || (w / scale);
          var quality = 0.7;  // 默认图片质量为0.7
          //生成canvas
          var canvas = document.createElement('canvas');
          var ctx = canvas.getContext('2d');
          // 创建属性节点
          var anw = document.createAttribute("width");
          anw.nodeValue = w;
          var anh = document.createAttribute("height");
          anh.nodeValue = h;
          canvas.setAttributeNode(anw);
          canvas.setAttributeNode(anh);
          ctx.drawImage(that, 0, 0, w, h);
          // 图像质量
          if (obj.quality && obj.quality <= 1 && obj.quality > 0) {
            quality = obj.quality;
          }
          // quality值越小，所绘制出的图像越模糊
          var base64 = canvas.toDataURL('image/jpeg', quality);
          // 回调函数返回base64的值
          callback(base64);
        }
      },
      //点击上传图片
      upload(item) {
        //判断是否是苹果，如果是删除capture属性
        var ua = navigator.userAgent.toLowerCase();
        var isIos = (ua.indexOf('iphone') != -1) || (ua.indexOf('ipad') != -1);
        if (isIos) {
          item.removeAttribute('capture')
        }
        //点击input上传
        item.click();
      },
      ...mapMutations({
        pitchOnImg: 'PITCHON_IMIG',
        pitchOnImgId: 'PITCHON_IMIG_ID',
      })
    },
    components: {
      LargerVersion,
      Loading
    }
  }
</script>


<style scoped lang="stylus" rel="stylesheet/stylus">
  @import "~common/stylus/variable"
  .photoWall
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    transition: all .5s cubic-bezier(.55, 0, .1, 1);
    z-index: 99;
    background: $background;
  .hint
    text-align:center;
    line-height :1.5rem;
    font-size :.4rem;
    span
      background: -webkit-linear-gradient(-300deg, #f65ecb, #9366f1);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
    .icon-jinggao
      color:#f5bd00;
  .title
    text-align: center;
    line-height: 1.47rem;
    position: relative;
    font-size: .54rem;
    color: $color-title;
    i
      position: absolute;
      top: 0;
      left: .44rem;
      color: $color-l-z;
      font-size: .62rem;
      display: line-block;
      line-height: 1.47rem;
    .editAdd
      position: absolute;
      top: 0;
      right: .5rem;
      line-height: 1.5rem;
      display: inline-block;
      font-size: .44rem;
      span
        margin-left: .2rem;

  ul
    overflow: hidden;
    li
      position: relative;
      width: 3.266rem;
      height: 3.266rem;
      float: left;
      img
        width: 3rem;
        height: 3rem;
      span
        position: absolute;
        top: -.2rem;
        right: -.1rem;
        z-index: 10;
        img
          width: .47rem;
          height: .47rem;
      .mask
        position: absolute;
        top: 0;
        left: .133rem;
        right: .133rem;
        bottom: .266rem;
        z-index: 9;
        line-height: 3.266rem;
        color: $color;
        font-size: .4rem;
        background: $background-shade;
        i
          color: $color;
          font-size :.8rem;

  .setting-content
    padding:0 .5rem;
    height: 9.8rem;
    text-align: center;
    li
      display: flex;
      justify-content: center;

  .sysimage
    position: fixed;
    bottom: 0;
    left: .5rem;
    right: .5rem;
    z-index: 99;
    background: $background;
    h3
      color: $color-system;
      font-size: .42rem;
      line-height: 1.35rem;

  .add
    position: fixed;
    width: 1.75rem;
    height: 1.75rem;
    left: 50%;
    bottom: .68rem;
    transform: translateX(-50%);
    img
      width: 100%;
      height: 100%;

  .empty
    position: absolute;
    top: 25%;
    left: 0;
    right: 0;
    text-align: center;
    font-size: .35rem;
    line-height: .55rem;
    color: $color-input-p;
    img
      width: 3rem;
      height: 3rem;
      margin-bottom: .55rem;

  .operation
    display: flex;
    text-align: center;
    line-height: 1.3rem;
    p
      width: 50%;
      background: -webkit-linear-gradient(-300deg, #f65ecb, #9366f1);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;


</style>
